﻿using Ninject;
using SelfManagement.Common.Log;
using SelfManagement.Data.Constant;
using SelfManagement.Mvc;
using SelfManagement.Mvc.Result;
using SelfManagement.Utility.Extensions;
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using SelfManagement.Web.Models.Session;
using SelfManagement.Web;
using System.Linq;

namespace SelfManagement.Web.Infrastructure
{
    public class CommonBaseController: BaseController
    {
        #region properties

        /// <summary>
        /// 记录日志
        /// </summary>
        [Inject]
        public ILogger Logger { get; set; }

        #endregion

        #region Action
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            if (!(new string[] { })
                .Contains(filterContext.RequestContext.RouteData.Values["controller"].ToString().ToLower())
               && filterContext.Result.GetType() == typeof(ViewResult))
            {
                ViewBag.UserSession = UserSession;
            }
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            JsonResultDataExtensions.Logger = Logger;//统一配置jsonResultData的日志对象

            //Viewbag里默认加载全站配置
            ViewBag.MaxImageLength = 4096;
            ViewBag.DefaultUserFaceImagePath = "~/assets/img/default-face.jpg";
            
        }

        /// <summary>
        /// 设置页面title
        /// </summary>
        /// <param name="title">主标题</param>
        /// <param name="subTitle">副标题（-后的）</param>
        [NonAction]
        protected virtual void SetPageTitle(string title, string subTitle = null)
        {
            ViewBag.Title = title;

            if (subTitle.IsNullOrWhiteSpace())
            {
                subTitle = "个人计划管理工具";
            }

            if (subTitle.IsNotNullAndNotWhiteSpace())
            {
                ViewBag.SubTitle = "-" + subTitle;
            }

            if (ViewBag.CurrentName == null)
            {
                ViewBag.CurrentName = ViewBag.Title;
            }
        }

        /// <summary>
        /// 设置页面导航数据
        /// </summary>
        /// <param name="currentName">当前页面名称</param>
        /// <param name="parentName">父页面名称</param>
        /// <param name="parentUrl">父页面url</param>
        [NonAction]
        protected virtual void SetBreadcrumb(string currentName = null, string parentName = null, string parentUrl = null)
        {
            ViewBag.CurrentName = currentName ?? ViewBag.Title;
            ViewBag.ParentName = parentName;
            ViewBag.ParentUrl = parentUrl;
        }

        /// <summary>
        /// 利用查询字符串构造分页视图需要的ViewData
        /// </summary>
        protected virtual ViewDataDictionary GetParameterFromQueryString()
        {
            ViewDataDictionary result = new ViewDataDictionary();
            foreach (var key in Request.QueryString.AllKeys)
            {
                if (!key.EqualsNoCase("page") && Request[key].IsNotNullAndNotWhiteSpace())
                {
                    result.Add(key, Request[key]);
                }
            }
            return result;
        }

        #endregion

        #region 辅助Redirect方法

        [NonAction]
        public virtual ActionResult RedirectToMessage(string message = null, string title = null, string returnUrl = null, int code = 500)
        {
            TempData["IsRedirect"] = true;
            TempData["Message"] = message;
            TempData["Title"] = title;
            TempData["ReturnUrl"] = returnUrl ?? Request.UrlReferrer?.ToString();

            return RedirectToRoute(RouteConfig.Message, new { RedirectUrl = returnUrl, code = code });
        }

        /// <summary>
        /// 重定向到公共错误页面
        /// </summary>
        /// <param name="message">错误消息</param>
        /// <param name="currentPage">引发错误的页面名称</param>
        /// <param name="returnUrl">重定向地址</param>
        [NonAction]
        public virtual ActionResult RedirectToError(string message = null, string currentPage = null, string returnUrl = null, int code = 500)
        {
            TempData["IsRedirect"] = true;
            TempData["Message"] = message;
            TempData["CurrentPage"] = currentPage;
            TempData["ReturnUrl"] = returnUrl ?? Request.UrlReferrer?.ToString();

            return RedirectToRoute(RouteConfig.Error, new { code = code, RedirectUrl = returnUrl });
        }

        #endregion

        #region 用户SESSION相关

        /// <summary>
        /// 获取用户session数据
        /// </summary>
        public virtual UserSession UserSession
        {
            get
            {
                return Session[SessionConstant.USER_SESSION] as UserSession;
            }
            set
            {
                Session[SessionConstant.USER_SESSION] = value;
            }
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        protected virtual void UserSignIn(UserSession userSession, bool rememberMe)
        {
            FormsAuthentication.SetAuthCookie(userSession.Identity, rememberMe);
            UserSession = userSession;
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        protected virtual void UserSignOut()
        {
            FormsAuthentication.SignOut();
            Session.Abandon();
        }

        #endregion
        

        #region 用戶方法

        /// <summary>
        /// 获取用户实际文件地址
        /// </summary>
        /// <param name="uid">用户id</param>
        /// <param name="uesrBasePath">用户基础路径, 参考SiteConstants.UserFaceSavePath</param>
        /// <returns></returns>
        protected virtual string GetUserPhysicalPath(string uid, string uesrBasePath, string fileName)
        {
            var userPath = HttpContext.Server.MapPath(string.Format(uesrBasePath, uid));
            if (!Directory.Exists(userPath))
            {
                Directory.CreateDirectory(userPath);
            }
            return Path.Combine(userPath, Path.GetFileName(fileName));
        }

        /// <summary>
        /// 获取上传的文件信息路径
        /// </summary>
        /// <param name="fieldName">表单名</param>
        /// <param name="uid">用户id</param>
        /// <param name="basePath">保存的文件名</param>
        /// <returns>返回一个相对web应用的路径</returns>
        protected virtual string SaveUserFile(string fieldName, string uid, string basePath, out string physicalPath)
        {
            HttpPostedFileBase file = Request.Files[fieldName];
            return SaveUserFile(file, uid, basePath, out physicalPath);
        }

        protected virtual string SaveUserFile(HttpPostedFileBase file, string uid, string basePath, out string physicalPath)
        {
            bool hasImg = file.IsNotNull() && file.ContentLength > 0 && file.FileName.IsNotNullAndNotWhiteSpace();
            var fileName = ""; //要保存的文件名
            physicalPath = ""; //要保存的物理路径
            if (hasImg)
            {
                fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
                physicalPath = GetUserPhysicalPath(uid, basePath, fileName);
                file.SaveAs(physicalPath); //保存图片
                return GetFileRelativePath(fileName, string.Format(basePath, uid));
            }
            return null;
        }

        protected virtual string SaveUserFile(string fieldName, string uid, string basePath)
        {
            string tempPhysicalPath;
            return SaveUserFile(fieldName, uid, basePath, out tempPhysicalPath);
        }
        #endregion
    }
}